package org.dragon.services.impls;

import jakarta.annotation.Resource;
import org.dragon.commons.Times;
import org.dragon.mappers.PermissionExtendMapper;
import org.dragon.models.Permission;
import org.dragon.services.PermissionService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/22 9:37
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionExtendMapper permissionExtendMapper;

    @Override
    public List<Permission> selectAll() {
        return permissionExtendMapper.selectAll();
    }

    @Cacheable(value = "permissions", key = "#id", sync = true)
    @Override
    public Permission findById(Long id) {
        return permissionExtendMapper.selectByPrimaryKey(id);
    }

    @Override
    public Permission findByCode(String code) {
        return permissionExtendMapper.findByCode(code);
    }

    @Override
    public List<Permission> findByPrivilegeId(Long id) {
        return permissionExtendMapper.findByPrivilegeId(id);
    }

    @CachePut(value = "permissions", key = "#permission.id")
    @Override
    public void save(Permission permission) {
        if (permission != null) {
            if (permission.getId() == null) {
                permission.setCreateTime(Times.now());
                permissionExtendMapper.insert(permission);
            } else
                permissionExtendMapper.updateByPrimaryKey(permission);
        }
    }

    @CacheEvict(value = "permissions", key = "#permission.id")
    @Override
    public void delete(Permission permission) {
        if (permission != null && permission.getId() != null) {
            permissionExtendMapper.deleteByPrimaryKey(permission.getId());
            permissionExtendMapper.deletePrivilegePermission(permission.getId());
            permissionExtendMapper.deleteRolePermission(permission.getId());
        }
    }

    @Override
    public void delete(Long id) {
        if (id != null) {
            permissionExtendMapper.deleteByPrimaryKey(id);
            permissionExtendMapper.deletePrivilegePermission(id);
            permissionExtendMapper.deleteRolePermission(id);
        }
    }

    @Override
    public void clear() {
        permissionExtendMapper.clear();
        permissionExtendMapper.clearPrivilegePermission();
        permissionExtendMapper.clearRolePermission();
    }
}
